package com.gjy.quartz.finance;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-30 19:50:50
 */
public class FinanceFileJobCtl {

    private static final Logger log = LoggerFactory.getLogger(FinanceFileJobCtl.class);

    public static void run(List<FinanceFileConfig> list) {
        for (FinanceFileConfig config : list) {
            createScheduler(config);
        }
    }

    private static void createScheduler(FinanceFileConfig config) {
        String taskKey = config.getTaskKey();

        String job = FinanceConstant.JOB + taskKey;
        String jobGroup = FinanceConstant.JOB_GROUP + taskKey;
        String trigger = FinanceConstant.TRIGGER + taskKey;
        String triggerGroup = FinanceConstant.TRIGGER_GROUP + taskKey;

        String cron = config.getCron();
        if (!CronExpression.isValidExpression(cron)) {
            log.error("cron表达式不符合要求: {}", cron);
            return;
        }

        StdSchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler;
        try {
            scheduler = factory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(taskKey, triggerGroup);
            JobKey jobKey = JobKey.jobKey(job, jobGroup);

            if (!scheduler.checkExists(jobKey)) {
                startScheduler(cron, scheduler, job, jobGroup, trigger, triggerGroup, config);
                return;
            }

            List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
            for (JobExecutionContext executingJob : executingJobs) {
                if (jobKey.equals(executingJob.getJobDetail().getKey())) {
                    log.warn("任务正在执行不能修改: {}", job);
                    return;
                }
            }

            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            String cronExpression = cronTrigger.getCronExpression();
            if (!cronExpression.equals(cron)) {
                scheduler.pauseTrigger(triggerKey); //停止触发器
                scheduler.unscheduleJob(triggerKey); //移除触发器
                scheduler.deleteJob(jobKey); // 删除job
                startScheduler(cron, scheduler, job, jobGroup, trigger, triggerGroup, config);
                log.info("定时任务: {}, cron修改:{}, {}", taskKey, cron, cronExpression);
            } else {
                log.info("定时任务: {}, cron未修改", taskKey);
            }
        } catch (Exception e) {
            log.error("定时任务异常: {}", taskKey);
            log.error("{}", e.getMessage());
        }
    }

    private static void startScheduler(String cron, Scheduler scheduler, String job, String jobGroup, String trigger, String triggerGroup, FinanceFileConfig config) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(FinanceFileJob.class)
                .withIdentity(job, jobGroup)
                .usingJobData(FinanceConstant.TASK_KEY, config.getTaskKey())
                .build();

        Trigger t = TriggerBuilder.newTrigger()
                .withIdentity(trigger, triggerGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();
        scheduler.scheduleJob(jobDetail, t);
        scheduler.start();
    }

}
